﻿/*********************************************
 创建者：  george
 创建时间：2016-11-01
 功能说明：部门管理(公司组织架构)
 ********************************************/
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Systems;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseAPI
{
    [Description("部门管理(公司组织架构)")]
    public class DeptHandler : BaseHandler
    {
        /// <summary>
        /// 创建部门编号
        /// </summary>
        /// <param name="parentCode">父级代码</param>
        /// <param name="dc"></param>
        /// <returns></returns>
        private string CreateDeptCode(string parentCode, SysEntities dc = null)
        {
            if (parentCode == "Root") return "1";
            if (dc == null) dc = new SysEntities();
            var deptCode = dc.sys_dept.Where(t => t.ParentCode == parentCode).Max(t => t.DeptCode);
            if (string.IsNullOrWhiteSpace(deptCode))
                return parentCode + "01";
            var maxID = Convert.ToDouble(deptCode);
            return (maxID+1).ToString();
        }

        [JsonType]
        [Description("创建部门")]
        [ReturnType(typeof(int),"0-成功")]
        public ApiResult Create([ParamDescription("输入参数")]model.DeptData.CreateData param)
        {
            if (param == null) return Error("参数对象为空");
            //if(string.IsNullOrWhiteSpace(param.DeptCode)) return Error("部门编码不能为空");
            if (string.IsNullOrWhiteSpace(param.DeptContent)) return Error("部门名称不能为空");
            //if (string.IsNullOrWhiteSpace(param.DeptName)) return Error("部门全称不能为空");
            if (string.IsNullOrWhiteSpace(param.ParentCode)) return Error("父级代码不能为空");
            //if (!string.IsNullOrWhiteSpace(param.DeptCode) && param.DeptCode.Length > 20) return Error("【部门编码】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.DeptName) && param.DeptName.Length > 120) return Error("【部门全称】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.CostCode) && param.CostCode.Length > 50) return Error("【成本中心编码】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.DeptContent) && param.DeptContent.Length > 200) return Error("【部门名称】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.StoreCode) && param.StoreCode.Length > 50) return Error("【店铺编号】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.StoreAddr) && param.StoreAddr.Length > 500) return Error("【店铺地址】长度超出限制");

            if (param.Grade<=0) return Error("无效的层级代码");
            if (param.ParentID <= 0) return Error("无效的父级ID");
            if (param.ParentID == 1 && string.IsNullOrWhiteSpace(param.CompanyID)) return Error("公司代码不能为空");
            var dc = new SysEntities();
            if (!string.IsNullOrWhiteSpace(param.CompanyID) &&
                dc.sys_dept.Any(d => d.CompanyID == param.CompanyID && d.IsRemove != true))
                return Error($"公司代码【{param.CompanyID}】已存在");
                var data = new sys_dept
            {
                CompanyID = param.CompanyID,
                CostCode = param.CostCode,
                DepartMent = param.DepartMent,
                DeptCode = CreateDeptCode(param.ParentCode, dc),
                DeptContent = param.DeptContent,
                DeptName = param.DeptName,
                Grade = param.Grade,
                IsRemove = false,
                Kind = param.Kind,
                operater = this.UserId,
                ParentCode = param.ParentCode,
                ParentID = param.ParentID,
                Restsetid = param.Restsetid,
                Sort = param.Sort,
                StoreAddr = param.StoreAddr,
                StoreCode = param.StoreCode
            };
            dc.sys_dept.Add(data);
            try
            {
                dc.SaveChanges();
            }catch(Exception ex)
            {
                return Error(ex.Message);  
            }
            return Success(0);
        }

        [JsonType]
        [Description("编辑部门")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Modify([ParamDescription("输入参数")]model.DeptData.ModifyData param)
        {
            if (param == null) return Error("参数对象为空");
            //if(string.IsNullOrWhiteSpace(param.DeptCode)) return Error("部门编码不能为空");
            if (string.IsNullOrWhiteSpace(param.DeptContent)) return Error("部门名称不能为空");
            if (string.IsNullOrWhiteSpace(param.DeptName)) return Error("部门全称不能为空");
            if (string.IsNullOrWhiteSpace(param.ParentCode)) return Error("父级代码不能为空");
            if (param.Grade <= 0) return Error("无效的层级代码");
            if (param.ParentID <= 0) return Error("无效的父级ID");
            if (param.ParentID == 1 && string.IsNullOrWhiteSpace(param.CompanyID)) return Error("公司代码不能为空");
            //if (!string.IsNullOrWhiteSpace(param.DeptCode) && param.DeptCode.Length > 20) return Error("【部门编码】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.DeptName) && param.DeptName.Length > 120) return Error("【部门全称】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.CostCode) && param.CostCode.Length > 50) return Error("【成本中心编码】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.DeptContent) && param.DeptContent.Length > 200) return Error("【部门名称】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.StoreCode) && param.StoreCode.Length > 50) return Error("【店铺编号】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.StoreAddr) && param.StoreAddr.Length > 500) return Error("【店铺地址】长度超出限制");
            var dc = new SysEntities();
            if (!string.IsNullOrWhiteSpace(param.CompanyID) &&
                dc.sys_dept.Any(d => d.CompanyID == param.CompanyID && d.DeptID != param.DeptID && d.IsRemove != true))
                return Error($"公司代码【{param.CompanyID}】已存在");
            var query = dc.sys_dept.FirstOrDefault(t => t.DeptID == param.DeptID);
            if (query==null) return Error("无数据");
            query.CompanyID = param.CompanyID;
            query.CostCode = param.CostCode;
            query.DepartMent = param.DepartMent;
            query.DeptContent = param.DeptContent;
            query.DeptName = param.DeptName;
            query.Kind = param.Kind;
            query.Restsetid = param.Restsetid;
            query.Sort = param.Sort;
            query.StoreAddr = param.StoreAddr;
            query.StoreCode = param.StoreCode;
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [Description("移除部门")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Remove([ParamDescription("部门ID")]int DeptID)
        {
            var dc = new SysEntities();
            //if (dc.sys_module_button.Any(t => t.ButtonID == ID)) return Error("按钮已被引用，无法删除");
            var post = dc.sys_Post.FirstOrDefault(t => t.DeptID == DeptID && t.IsRemove == false);
            var role = dc.sys_role.FirstOrDefault(t => t.DeptID == DeptID && t.IsRemove == false);
            var user = dc.sys_v_userInfo.FirstOrDefault(t => t.DeptID == DeptID && t.IsRemove == false);
            if (post != null && role != null && user != null) return Error("该部门存在岗位、角色或用户信息，无法删除！");
            var query = dc.sys_dept.FirstOrDefault(t => t.DeptID == DeptID);
            if (query == null) return Error("无数据");
            //逻辑删除
            query.IsRemove = true;
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [Description("获取指定部门信息")]
        [ReturnType(typeof(model.DeptData.ModifyData))]
        public ApiResult GetID([ParamDescription("部门ID")]int DeptID)
        {
            var dc = new SysEntities();
            var query = dc.sys_dept.FirstOrDefault(t => t.DeptID == DeptID);
            if (query == null) return Error("无数据");
            var result = new model.DeptData.ModifyData
            {
                CompanyID = query.CompanyID,
                CostCode = query.CostCode,
                DepartMent = query.DepartMent,
                DeptContent = query.DeptContent,
                DeptCode = query.DeptCode,
                DeptID = query.DeptID,
                DeptName = query.DeptName,
                Grade = (int) query.Grade,
                Kind = query.Kind,
                ParentCode = query.ParentCode,
                ParentID = (int) query.ParentID,
                Restsetid = query.Restsetid,
                Sort = (int) query.Sort,
                StoreAddr = query.StoreAddr,
                StoreCode = query.StoreCode
            };
            return Success(result);
        }

        [Description("获取部门结构")]
        [ReturnType(typeof(IList<model.DeptData.ModifyData>))]
        public ApiResult GetList([ParamDescription("部门ID")]string DeptCode="")
        {
            var dc = new SysEntities();
            var querys = dc.sys_dept.Where(t=>t.IsRemove==false);
            var result = (from c in querys
                where c.DeptCode == DeptCode && c.IsRemove == false
                select c).ToList().Select(o => new model.DeptData.DeptListData
            {
                CompanyID = o.CompanyID,
                DepartMent = o.DepartMent,
                DeptCode = o.DeptCode,
                DeptContent = o.DeptContent,
                DeptID = o.DeptID,
                CostCode = o.CostCode,
                DeptName = o.DeptName,
                Grade = (int) o.Grade,
                Kind = o.Kind,
                ParentCode = o.ParentCode,
                ParentID = (int) o.ParentID,
                Restsetid = o.Restsetid,
                Sort = (int) o.Sort,
                StoreAddr = o.StoreAddr,
                StoreCode = o.StoreCode,
                Children = GetChildren(querys, o.DeptCode)
            }).ToList();
           
            return Success(result);
        }

        public List<model.DeptData.DeptListData> GetChildren(IQueryable<sys_dept> comments, string DeptCode)
        {
            return (from c in comments
                    where c.ParentCode == DeptCode && c.IsRemove == false
                    select c).ToList().Select(o => new model.DeptData.DeptListData
                    {
                        DepartMent = o.DepartMent,
                        DeptCode = o.DeptCode,
                        DeptContent = o.DeptContent,
                        DeptID = o.DeptID,
                        CostCode = o.CostCode,
                        DeptName = o.DeptName,
                        Grade = (int)o.Grade,
                        Kind = o.Kind,
                        ParentCode = o.ParentCode,
                        ParentID = (int)o.ParentID,
                        Restsetid = o.Restsetid,
                        Sort = (int)o.Sort,
                        StoreAddr = o.StoreAddr,
                        StoreCode = o.StoreCode,
                        Children = GetChildren(comments, o.DeptCode)
                    }).ToList();
        }

        /// Writer：梁家健
        /// Create Date：2017-06-22
        [MustLogin]
        [Description("公司列表")]
        [ReturnType(typeof(IList<model.DeptData.CoreModel>))]
        public ApiResult GetDeptList()
        {
            var dc = new SysEntities();
            var query =
                dc.sys_dept.Where(d => d.CompanyID != null && d.ParentCode == "1" && d.IsRemove != true)
                    .Select(d => new model.DeptData.CoreModel
                    {
                        CompanyID = d.CompanyID,
                        DeptCode = d.DeptCode,
                        DeptContent = d.DeptContent,
                    }).ToList();
            return Success(query);
        }
    }
}
